﻿using AutoMapper;
using MiniExcelLibs;
using MiniExcelLibs.OpenXml;

namespace OP10.ViewModels
{
    public class IOMonitorViewModel : BaseViewModel
    {

        private readonly IMapper _mapper;

        public IOMonitorViewModel(IRegionManager regionManager, IMapper mapper) : base(regionManager)
        {

            _mapper = mapper;


            GetPLCIOConfigs4Excel(@".\Documents\OP10IO表.xlsx");

            //开启定时器任务
            DispatcherTimer dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Interval = TimeSpan.FromMilliseconds(200);
            dispatcherTimer.Tick += OnTick;
            dispatcherTimer.Start();

        }

        private void OnTick(object? sender, EventArgs e)
        {
            //0-160
            for (int i = 0; i < ObIPointDatas.Count; i++)
            {
                ObIPointDatas[i].IOStatus = IO_Global.IO_R[i];
            }

            for (int i = 0; i < ObQPointDatas.Count; i++)
            {
                ObQPointDatas[i].IOStatus = IO_Global.IO_R[i +160];
            }
          
        }

        public List<IOExcelDto> listIO { get; set; } = new List<IOExcelDto>();
        private void GetPLCIOConfigs4Excel(string path)
        {
            //查询所有sheet
            var sheetNames = MiniExcel.GetSheetNames(path);
            var config = new OpenXmlConfiguration()
            {
                FillMergedCells = true,
            };

            foreach (var sheetName in sheetNames)
            {
               if (sheetName =="I点")
                {
                    var listIO = MiniExcel.Query<IOExcelDto>(path, sheetName, configuration: config).ToList();
                    var list = _mapper.Map<List<IOMonitorModel>>(listIO);
                    ObIPointDatas =new ObservableCollection<IOMonitorModel>(list);
                }

               else if(sheetName=="Q点")
                {
                    var listIO = MiniExcel.Query<IOExcelDto>(path, sheetName, configuration: config).ToList();
                    var list = _mapper.Map<List<IOMonitorModel>>(listIO);

                    ObQPointDatas = new ObservableCollection<IOMonitorModel>(list);

                }


            }
        }


  

        private ObservableCollection<IOMonitorModel> _ObIPointDatas;

        public ObservableCollection<IOMonitorModel> ObIPointDatas
        {
            get { return _ObIPointDatas??(_ObIPointDatas=new ObservableCollection<IOMonitorModel>()); }
            set { SetProperty(ref _ObIPointDatas, value); }
        }

        private ObservableCollection<IOMonitorModel> _ObQPointDatas;

        public ObservableCollection<IOMonitorModel> ObQPointDatas
        {
            get { return _ObQPointDatas??(_ObQPointDatas=new ObservableCollection<IOMonitorModel>()); }
            set { SetProperty(ref _ObQPointDatas, value); }
        }
    }
}
